package com.cy.myblog.service.impl;

import com.cy.myblog.dao.ClassifyDaoI;
import com.cy.myblog.model.Tarticle;
import com.cy.myblog.model.Tclassify;
import com.cy.myblog.service.ArticleServiceI;
import com.cy.myblog.service.ClassifyServiceI;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service("classifySerivce")
public class ClassifyServiceImpl implements ClassifyServiceI {

	private ClassifyDaoI classifyDao;
	private ArticleServiceI articleService;

	@Resource(name = "articleService")
	public void setArticleService(ArticleServiceI articleService) {
		this.articleService = articleService;
	}

	@Autowired
	public void setClassifyDao(ClassifyDaoI classifyDao) {
		this.classifyDao = classifyDao;
	}

	public Tclassify save(Tclassify classify) {
		int sort = getMaxSort();
		classify.setSort(++sort);
		classifyDao.save(classify);
		return classify;
	}

	public Tclassify getById(Integer id) {
		Tclassify tcla = classifyDao.getById(Tclassify.class, id);
		return tcla;
	}

	@Override
	public void delete(Tclassify tclassify) {
		Tclassify defualtClassify = getByName("默认分类");
		if(tclassify.getArticles().size() > 0 || !tclassify.getArticles().isEmpty()){
			for(Tarticle article : tclassify.getArticles()){
				article.setTclassify(defualtClassify);
				articleService.update(article);
			}
		}
		classifyDao.delete(tclassify);
	}

	@Override
	public void update(Tclassify tclassify) {
		Set<Tarticle> arts =new HashSet<Tarticle>();
		Tclassify tclify = getById(tclassify.getId());
		if( tclify!= null){
			BeanUtils.copyProperties(tclassify,tclify,new String[]{"articles"});
		}else{
			save(tclassify);
		}

		if(tclassify.getArticles().size() > 0 || !tclassify.getArticles().isEmpty()) {
			for (Tarticle article : tclassify.getArticles()) {
				Tarticle temp = articleService.getById(article.getId());
				temp.setTclassify(tclassify);
				arts.add(temp);
				articleService.update(temp);
			}
		}
	}

	@Override
	public List<Tclassify> findAll() {
		String hql="from Tclassify order by sort";
		List<Tclassify> list = classifyDao.find(hql);
		return list;
	}

	@Override
	public Tclassify getByName(String classifyName) {
		String hql = "from Tclassify where classifyname = :classifyname";
		if(StringUtils.isNotEmpty(classifyName)){
		    Map<String,Object> params = new HashMap<String,Object>();
			params.put("classifyname",classifyName);
			return classifyDao.getByHql(hql,params);
		}
		return null;
	}

	@Override
	public int getMaxSort() {
		String hql = "select max(sort) from Tclassify";
		Object obj = classifyDao.getByHql(hql);
		if(obj != null) {
			Integer i = Integer.parseInt(obj.toString());
			return i;
		}else{
			return 0;
		}
	}

}
